package com.ice_col.surfaceviewturntable;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

/**
 * Created by Administrator on 2015/9/10 0010.
 */
public abstract class SurfaceViewTemp extends SurfaceView implements SurfaceHolder.Callback,Runnable{

    protected Thread mThread;
    protected boolean isRunning;
    protected SurfaceHolder mSurfaceHolder;
    protected Canvas mCanvas;


    public SurfaceViewTemp(Context context) {
      super(context);
    }

    public SurfaceViewTemp(Context context, AttributeSet attrs) {
        super(context, attrs);
        mSurfaceHolder=getHolder();
        mSurfaceHolder.addCallback(this);
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isRunning=true;
        mThread=new Thread(this);
        mThread.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isRunning=false;
    }

    @Override
    public void run() {
        while(isRunning){
            long start=System.currentTimeMillis();
            draw();
            long stop=System.currentTimeMillis();
            if((stop-start)<50){
                try {
                    Thread.sleep(50-(stop-start));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    private void draw(){
        try {
            mCanvas = mSurfaceHolder.lockCanvas();
            if (mCanvas != null) {
                doDraw();
            }
        }catch (Exception e){

        }finally {
            if(mCanvas!=null){
                mSurfaceHolder.unlockCanvasAndPost(mCanvas);
            }
        }
    }

    protected abstract void doDraw();
}
